package com.zaaach.citypicker;

import android.Manifest;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.zaaach.citypicker.adapter.CityListAdapter;
import com.zaaach.citypicker.adapter.ResultListAdapter;
import com.zaaach.citypicker.db.DBManager;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.utils.StringUtils;
import com.zaaach.citypicker.view.SideLetterBar;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * Author Bro0cL on 2016/12/16.
 * 城市选择
 */
public class CityPickerActivity extends CheckPermissionsActivity implements View.OnClickListener, CheckPermissionsListener {
    public static final String KEY_PICKED_CITY = "picked_city";

    private LinearLayout mSearchLayout;
    private LinearLayout mLeftLayout;
    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private TextView cancelBtn;
    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private List<City> mResultCities;
    private DBManager dbManager;

    public static final Boolean HIDE_ALL_CITY = false;

    private AMapLocationClient mLocationClient;

    //城市定位
    private LocationClient mLocationClientCity = null;
    //返回城市名字字符串
    private String cityName=null;

    //Thread+Handler
    final static int MESSAGE_WHAT=11;
    final static int MESSAGE_WHAT1=12;
    final static String TAG="Message";
    private Handler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        mHandler= new Handler(){
            //在主线程中创建一个Handler，然后重写该Handler的handlerMessage方法，
            //可以看到该方法传入了一个参数Message，
            // 该参数就是我们从其他线程传递过来的信息
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MESSAGE_WHAT:
                        System.out.println("Handler收到的字符串："+msg.obj);
//                        String location = StringUtils.extractLocation((String)msg.obj, "莲池");
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, (String) msg.obj);
                        break;
                } }
        };

        //实现定位功能
        //创建定位客户端对象，参数要求是应用程序级别的环境上下文对象
        mLocationClientCity= new LocationClient(getApplicationContext());
        //动态申请权限
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},100);
        setContentView(R.layout.cp_activity_city_list);
        setStatusBar(this.getResources().getColor(R.color.businesstop));
        initData();
        initView();
//        initLocation();
//        System.out.println("定位到的城市为"+cityName);
//        请求权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            mLocationClient.startLocation();
        }else {
            requestPermissions(this, neededPermissions, this);
        }

    }
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        new Thread(){
            @Override
            public void run() {
                Message message = mHandler.obtainMessage(MESSAGE_WHAT);
                message.obj = null;

                //grantResults数组当中存储的是用户选择的结果，0表示允许，-1表示拒绝
                if(requestCode==100&&grantResults[0]==0){
                    //创建locationclientoption对象
                    LocationClientOption locationClientOption=new LocationClientOption();
                    //配置定位参数
                    //设置打开GPS
                    locationClientOption.setOpenGps(true);
                    //设置坐标系类型
                    locationClientOption.setCoorType("bd09ll");//百度的经纬度坐标系
                    //设置采用的定位模式(建议使用低功耗的定位模式)
                    locationClientOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
//            locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                    //将定位参数应用到定位客户端
                    mLocationClientCity.setLocOption(locationClientOption);
                    //设置定位成功的监听器(实现异步定位操作，定位成功后会自动调用接口中的方法)
                    mLocationClientCity.registerLocationListener(new BDAbstractLocationListener() {
                        @Override
                        public void onReceiveLocation(BDLocation bdLocation) {
                            //定位成功后自动执行:定位成功后位置信息保存在BDLocation对象中
                            double latitude=bdLocation.getLatitude();//纬度
                            double longtitude=bdLocation.getLongitude();//经度
                            int code=bdLocation.getLocType();//获取定位错误码
                            List<Address> result = null;
                            if (bdLocation != null) {
                                Geocoder gc = new Geocoder(CityPickerActivity.this, Locale.getDefault());
                                try {
                                    result = gc.getFromLocation(bdLocation.getLatitude(),
                                            bdLocation.getLongitude(), 1);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
//                    Log.e("定位成功","定位结果"+code+"纬度"+latitude+"经度"+longtitude+"城市名字"+result.get(0).getLocality());
//                    System.out.println("城市名字"+result.get(0).getLocality());/
                            cityName=result.get(0).getLocality();
                            System.out.println("第一次获取到的城市定位："+cityName);
                        }
                    });

                    //开启定位
                    mLocationClientCity.start();
                    while(true){
                        if(cityName!=null){
                            message.obj=cityName;
                            System.out.println("Thread发出的字符串:"+message.obj);
                            mHandler.sendMessage(message);
                            break;
                        }
                    }

                }
            }
        }.start();

    }
//    private void initLocation() {
//        //long自己加的百度定位
//        //创建locationclientoption对象
//        LocationClientOption locationClientOption=new LocationClientOption();
//        //配置定位参数
//        //设置打开GPS
//        locationClientOption.setOpenGps(true);
//        //设置坐标系类型
//        locationClientOption.setCoorType("bd09ll");//百度的经纬度坐标系
//        //设置采用的定位模式(建议使用低功耗的定位模式)
//        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
////            locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//        //将定位参数应用到定位客户端
//        mLocationClientCity.setLocOption(locationClientOption);
//        //设置定位成功的监听器(实现异步定位操作，定位成功后会自动调用接口中的方法)
//        mLocationClientCity.registerLocationListener(new BDAbstractLocationListener() {
//            @Override
//            public void onReceiveLocation(BDLocation bdLocation) {
//                //定位成功后自动执行:定位成功后位置信息保存在BDLocation对象中
//                double latitude=bdLocation.getLatitude();//纬度
//                double longtitude=bdLocation.getLongitude();//经度
//                int code=bdLocation.getLocType();//获取定位错误码
//                List<Address> result = null;
//                if (bdLocation != null) {
//                    Geocoder gc = new Geocoder(CityPickerActivity.this, Locale.getDefault());
//                    try {
//                        result = gc.getFromLocation(bdLocation.getLatitude(),
//                                bdLocation.getLongitude(), 1);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
////                    Log.e("定位成功","定位结果"+code+"纬度"+latitude+"经度"+longtitude+"城市名字"+result.get(0).getLocality());
////                    System.out.println("城市名字"+result.get(0).getLocality());/
//                cityName=result.get(0).getLocality();
//                System.out.println("获取到的城市定位："+cityName);
//            }
//        });
        //开启定位
//        mLocationClientCity.start();

//        //拷贝的，不是自己加的
//        mLocationClient = new AMapLocationClient(this);
//        AMapLocationClientOption option = new AMapLocationClientOption();
//        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        option.setOnceLocation(true);
//        mLocationClient.setLocationOption(option);
//        mLocationClient.setLocationListener(new AMapLocationListener() {
//            @Override
//            public void onLocationChanged(AMapLocation aMapLocation) {
//                if (aMapLocation != null) {
//                    if (aMapLocation.getErrorCode() == 0) {
//                        String province = aMapLocation.getProvince();
//                        String city = aMapLocation.getCity();
////                        cityName=city;
//                        String district = aMapLocation.getDistrict();
//                        String location = StringUtils.extractLocation(cityName, district);
////                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
//                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
//                        System.out.println("高德定位成功");
//                    } else {
//                        //定位失败
//                        System.out.println("高德定位失败1");
////                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
//                        String city = aMapLocation.getCity();
//                        System.out.println("高德定位失败3");
////                        cityName=city;
//                        String district = aMapLocation.getDistrict();
//                        System.out.println("city:"+city);
//                        System.out.println("高德定位失败4");
//                        String location = StringUtils.extractLocation(city, district);
//                        System.out.println("高德定位失败5");
////                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
//                        mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
//                        System.out.println("高德定位失败2");
//                    }
//                }
//
//            }
//        });
//
//    }

    private void initData() {
        dbManager = new DBManager(this);
        dbManager.copyDBFile();
        mAllCities = dbManager.getAllCities();
//        mAllCities.clear();
        mCityAdapter = new CityListAdapter(this, mAllCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {
                backWithData(name);
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                requestPermissions(CityPickerActivity.this, neededPermissions, CityPickerActivity.this);
            }
        });

        mResultAdapter = new ResultListAdapter(this, null);
    }

    private void initView() {
        mLeftLayout = (LinearLayout) findViewById(R.id.left_layout);
        mLeftLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mListView = (ListView) findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);
        mSearchLayout = (LinearLayout) findViewById(R.id.search_layout);
        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });

        searchBox = (EditText) findViewById(R.id.et_search);
        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
                    mResultCities = dbManager.searchCity(keyword);
                    if (mResultCities == null || mResultCities.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(mResultCities);
                    }
                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                backWithData(mResultAdapter.getItem(position).getName());
            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);
        cancelBtn = (TextView) findViewById(R.id.tv_search_cancel);

        clearBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        if (HIDE_ALL_CITY) {
            mSearchLayout.setVisibility(View.GONE);
            mLetterBar.setVisibility(View.GONE);
        }
    }

    private void backWithData(String city){
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, city);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_search_clear) {
            searchBox.setText("");
            clearBtn.setVisibility(View.GONE);
            emptyView.setVisibility(View.GONE);
//            mResultListView.setVisibility(View.GONE);
            mResultCities = null;
        } else if (i == R.id.tv_search_cancel) {
            finish();
        }
    }

    @Override
    public void onGranted() {
//        mLocationClient.startLocation();
    }

    @Override
    public void onDenied(List<String> permissions) {
        Toast.makeText(this, "权限被禁用，请到设置里打开", Toast.LENGTH_SHORT).show();
        mCityAdapter.updateLocateState(LocateState.FAILED, null);
    }


}
